package br.com.chat.client;

import java.util.Collections;
import java.util.List;

import br.com.chat.Message;
import br.com.chat.User;
import br.com.chat.rmi.ChatManager;
import br.com.chat.rmi.MessageReceiver;
import br.com.chat.rmi.MessageSender;
import br.com.chat.utils.RemoteUtil;

public class Client {
    
    private User user;
    
    public Client(User user) {
        super();

        this.user = user;
    }

    public void sendMessage( String content ){
        MessageSender sender = RemoteUtil.loadSender();
        
        try {
            sender.sendMessage(user, new User("TODOS"), content);
//            sender.sendMessage(CryptographyMessage.encrypt(new Message(user, new User("TODOS"), content)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public List<Message> receiveMessage(){
        MessageReceiver receiver = RemoteUtil.loadReceiver();
        
        try {
            return receiver.receive(user);
//            List<Message> receive = receiver.receive(user);
//            
//            if ( receive.size() > 0 ){
//                return CryptographyMessage.decrypt(receive);
//            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return Collections.emptyList();
    }
    
    public boolean isLoggedIn(){
        ChatManager manager = RemoteUtil.loadManager();
        
        try {
            return manager.isLoggedIn(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    public void login(){
        ChatManager manager = RemoteUtil.loadManager();
        
        try {
            if ( !manager.isLoggedIn(user)){
                manager.login(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void logout(){
        ChatManager manager = RemoteUtil.loadManager();
        
        try {
            manager.logout(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
